﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

using Sunyi.Project.WebPoint.Common;

using ActivitySystem.DataContract;
using ActivitySystem.DataAccessController;


namespace ActivitySystem.BusinessLogic
{
    public partial class ParticipationManager
    {
        public void JoinActivity(Guid userId, Guid activityId, int fellow = 0, string comments = null)
        {
            if (fellow < 0)
            {
                throw new ArgumentOutOfRangeException("fellow", "Fellow can only be non-negative");
            }

            ActivityManager activityManager = new ActivityManager();
            Activity activity = activityManager.Select(activityId);

            if (activity.EndTime < DateTime.Now)
            {
                throw new Exception("Activity already ended");
            }

            Participation newParticipation = new Participation();
            newParticipation.Id = Guid.NewGuid();
            newParticipation.UserId = userId;
            newParticipation.ActivityId = activityId;
            newParticipation.Fellow = fellow;
            newParticipation.Comments = comments;
            newParticipation.IsApproved = activity.IsPublic;
            newParticipation.IsActive = true;
            newParticipation.InsertTimeStamp = DateTime.Now;
            newParticipation.UpdateTimeStamp = DateTime.Now;

            Collection<Participation> oldParticipations = controller.SelectByUserIdAndActivityId(userId, activityId);

            TransactionHelper.ProcessTransaction(new Action(delegate
            {
                if (oldParticipations != null)
                {
                    foreach (Participation oldParticipation in oldParticipations)
                    {
                        Delete(oldParticipation.Id);
                    }
                }
                Insert(newParticipation);
            }));
        }

        public void QuitActivity(Guid userId, Guid activityId)
        {
            ActivityManager activityManager = new ActivityManager();
            Activity activity = activityManager.Select(activityId);

            if (activity.StartTime > DateTime.Now)
            {
                throw new Exception("Activity is already started");
            }

            if (activity.LauncherId == userId)
            {
                throw new Exception("Launcher cannot quit");
            }

            Collection<Participation> participations = controller.SelectByUserIdAndActivityId(userId, activityId);
            foreach (Participation participation in participations)
            {
                controller.Delete(participation.Id);
            }
        }
    }
}
